package leetcode.medium.limit100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author yaoyao1.liu@zhaopin.com.cn
 * @since 2022-11-10 14:02
 **/
public class No57 {
    public static void main(String[] args) {
        No57 no57 = new No57();
        int[][] insert = no57.insert(new int[][]{{1, 2}, {3, 5}, {6, 7}, {8, 10}, {12, 16}}, new int[]{4, 8});
        System.out.println(Arrays.deepToString(insert));
    }

    public int[][] insert(int[][] intervals, int[] newInterval) {
        if (intervals.length == 0) {
            return new int[][]{newInterval};
        }
        List<int[]> merged = new ArrayList<>();
        int[][] newa = new int[intervals.length + 1][2];
        System.arraycopy(intervals, 0, newa, 0, intervals.length);
        newa[intervals.length] = newInterval;

        Arrays.sort(newa, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return Integer.compare(o1[0], o2[0]);
            }
        });
        for (int[] interval : newa) {
            int l = interval[0];
            int r = interval[1];
            if (merged.size() == 0 || merged.get(merged.size() - 1)[1] < l) {
                merged.add(new int[]{l, r});
            } else {
                merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], r);
            }
        }
        return merged.toArray(new int[merged.size()][]);
    }


}
